package org.zephyr.struct.bridge.ex;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * 读取XML方法
 */
public class ReadXML {
     public static Object getObject(String args){
         try {
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             DocumentBuilder builder = dbf.newDocumentBuilder();
             Document doc;
             doc=builder.parse(new File("src/main/java/org/zephyr/struct/bridge/ex/config.xml"));
             //获取包含类名的文本节点
             NodeList nl=doc.getElementsByTagName("className");
             Node classNode=null;
             if(args.equals("color")){
                 classNode=nl.item(0).getFirstChild();
             }else if(args.equals("bag")){
                 classNode=nl.item(1).getFirstChild();
             }
             String cName="org.zephyr.struct.bridge.ex."+classNode.getNodeValue();
             //通过类名生成实例对象并将其返回
             Class<?> c=Class.forName(cName);
             Object obj=c.getDeclaredConstructor().newInstance();
             return obj;
         }catch (Exception e){
            e.printStackTrace();
            return null;
         }
     }
}
